 package com.example.food.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.food.adapter.Alacarteapter;
import com.example.food.adapter.DisheslistlistApter;
import com.example.food.adapter.Storereviewapter;
import com.example.food.bean.AlacarteBean;
import com.example.food.bean.DisheslistlistBean;
import com.example.food.bean.SeekUserBean;
import com.example.food.bean.StoreDetailBean;
import com.example.food.bean.StorereviewBean;
import com.example.home.R;
import com.example.home.tool.OKHttpTool;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;

import static com.example.home.tool.StaticActi.ip;

public class StoreDetailActivity extends AppCompatActivity {
    private ImageView imgUrl;
    private ImageView back;
    private ImageView collect;
    private ImageView img;
    private TextView name;
    private TextView score;
    private TextView saleQuantity;
    private TextView avgCost;
    private TabLayout tabList;
    private RecyclerView classify;
    private RecyclerView vegetable;
    private LinearLayout settlement;
    private ImageView iumgurl;
    private TextView price_money;
    private RecyclerView rcvComment;
    private RelativeLayout re2;
    private ImageView imgurlSjangjia;
    private TextView address;
    private TextView introduction;
    private StoreDetailBean nearBean;
    private String money_total;
    private TextView settle;
    private String recomId;
    private SeekUserBean seekUserBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_detail);
        Intent intent = getIntent();
        recomId = intent.getStringExtra("recomId");
        initView();
        getData(recomId);
        setTab("点菜");

        seekUserCheck();
        Log.v("xhf","id="+recomId);
    }


    private void setTab(String name) {
        ArrayList<String> list = new ArrayList<>();
        list.add("点菜");
        list.add("评价");
        list.add("商家介绍");

        for (int i = 0; i < list.size(); i++) {
            TabLayout.Tab tab = tabList.newTab();
            tab.setText(list.get(i));
            tabList.addTab(tab);
        }
        mytabaddlister();
    }

    private void mytabaddlister() {
        tabList.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                String name = tab.getText().toString();
                Integer id = nearBean.getData().getId();
                Integer themeId = nearBean.getData().getThemeId();

                if ("点菜".equals(name)) {
                    //菜品
                    alacarte(id, themeId);
                    //菜品列表
                    disheslistlist(id);
                } else if ("评价".equals(name)) {
                    storereview(id);
                } else if ("商家介绍".equals(name)) {
                    merchantintroduction(nearBean);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        TabLayout.Tab defaultTab = tabList.getTabAt(0);
        if (defaultTab != null) {
            defaultTab.select();
        }
    }

    private void disheslistlist(Integer id) {
        rcvComment.setVisibility(View.GONE);
        re2.setVisibility(View.GONE);
        settlement.setVisibility(View.VISIBLE);
        classify.setVisibility(View.VISIBLE);
        vegetable.setVisibility(View.VISIBLE);
        OKHttpTool.doNetRequest("prod-api/api/takeout/category/list?sellerId=" + id,
                OKHttpTool.GET,
                DisheslistlistBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        DisheslistlistBean disheslistlistBean = (DisheslistlistBean) obj;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                classify.setLayoutManager(new LinearLayoutManager(StoreDetailActivity.this));
                                classify.setAdapter(new DisheslistlistApter(StoreDetailActivity.this, disheslistlistBean.getData()));
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                });

    }


    private void alacarte(Integer id, Integer themeId) {
        rcvComment.setVisibility(View.GONE);
        re2.setVisibility(View.GONE);
        settlement.setVisibility(View.VISIBLE);
        classify.setVisibility(View.VISIBLE);
        vegetable.setVisibility(View.VISIBLE);

        OKHttpTool.doNetRequest("prod-api/api/takeout/product/list?sellerId=" + themeId + "&categoryId=" + id,
                OKHttpTool.GET,
                AlacarteBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        AlacarteBean alacarteBean = (AlacarteBean) obj;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                vegetable.setLayoutManager(new LinearLayoutManager(StoreDetailActivity.this));
                                Alacarteapter alacarteapter = new Alacarteapter(StoreDetailActivity.this, alacarteBean.getData());
                                vegetable.setAdapter(alacarteapter);
                                //点击跳转到结算
                                productsettlement(alacarteBean);
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }

    private void productsettlement(AlacarteBean alacarteBean) {
        settle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(StoreDetailActivity.this, ProductsettlementActivity.class);
                intent.putExtra("money", String.valueOf(money_total));
                if (alacarteBean != null) {
                    Gson gson = new Gson();
                    String json = gson.toJson(alacarteBean);
                    intent.putExtra("alacarteBean", json);
                }
                startActivity(intent);
            }
        });
    }

    private void storereview(Integer id) {
        classify.setVisibility(View.GONE);
        vegetable.setVisibility(View.GONE);
        settlement.setVisibility(View.GONE);
        rcvComment.setVisibility(View.VISIBLE);
        OKHttpTool.doNetRequest("prod-api/api/takeout/comment/list?sellerId=" + id,
                OKHttpTool.GET,
                StorereviewBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        StorereviewBean storereviewBean = (StorereviewBean) obj;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                rcvComment.setLayoutManager(new LinearLayoutManager(StoreDetailActivity.this));
                                rcvComment.setAdapter(new Storereviewapter(StoreDetailActivity.this, storereviewBean.getRows()));
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }

    private void merchantintroduction(StoreDetailBean nearBean) {
        classify.setVisibility(View.GONE);
        vegetable.setVisibility(View.GONE);
        settlement.setVisibility(View.GONE);
        rcvComment.setVisibility(View.GONE);
        re2.setVisibility(View.VISIBLE);
        StoreDetailBean.DataBean data = nearBean.getData();
        address.setText(data.getAddress());
        introduction.setText("商家简介:       " + data.getIntroduction());
        Glide.with(this).load(ip + data.getImgUrl()).into(imgurlSjangjia);
    }


    private void getData(String recomId) {
        OKHttpTool.doNetRequest("prod-api/api/takeout/seller/" + recomId,
                OKHttpTool.GET,
                StoreDetailBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        nearBean = (StoreDetailBean) obj;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                StoreDetailBean.DataBean data = nearBean.getData();
                                Glide.with(StoreDetailActivity.this).load(ip + data.getImgUrl()).into(imgUrl);
                                Glide.with(StoreDetailActivity.this).load(ip + data.getImgUrl()).into(img);
                                name.setText(data.getName());
                                avgCost.setText(String.valueOf(data.getAvgCost()) + "元/人");
                                score.setText(String.valueOf("评分：" + data.getScore()) + "分");
                                saleQuantity.setText(String.valueOf("月销：" + data.getSaleQuantity()) + "  +");
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }

    public void getMoney(BigDecimal money) {
        if (money.compareTo(BigDecimal.ZERO) != 0) {
            money_total = money.setScale(2, RoundingMode.HALF_UP).toString();
            price_money.setText(money_total);
        } else {
            price_money.setText("0");
        }
    }


    private void initView() {


        imgUrl = findViewById(R.id.imgUrl);
        back = findViewById(R.id.back);
        collect = findViewById(R.id.collect);
        img = findViewById(R.id.img);
        name = findViewById(R.id.name);
        score = findViewById(R.id.score);
        saleQuantity = findViewById(R.id.saleQuantity);
        avgCost = findViewById(R.id.avgCost);
        tabList = findViewById(R.id.tab_list);
        classify = findViewById(R.id.classify);
        vegetable = findViewById(R.id.vegetable);
        settlement = findViewById(R.id.settlement);
        iumgurl = findViewById(R.id.iumgurl);
        price_money = findViewById(R.id.price_money);
        rcvComment = findViewById(R.id.rcv_comment);
        re2 = findViewById(R.id.re2);
        imgurlSjangjia = findViewById(R.id.imgurl_sjangjia);
        address = findViewById(R.id.address);
        introduction = findViewById(R.id.introduction);
        settle = findViewById(R.id.settle);

        collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                seekUserCheck();
                if (seekUserBean.isIsCollect() ==true) {
                    deleteCollection();
                } else if(seekUserBean.isIsCollect() == false){
                    setCollection();
                }
            }
        });
    }

    private void seekUserCheck() {
        OKHttpTool.doNetRequest("prod-api/api/takeout/collect/check?sellerId=" + recomId,
                OKHttpTool.GET,
                SeekUserBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        seekUserBean = (SeekUserBean) obj;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (seekUserBean.isIsCollect()) {
                                    collect.setImageResource(R.drawable.huangixing);
                                } else {
                                    collect.setImageResource(R.drawable.shoucang);
                                }
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {
                        // 处理失败情况
                    }
                });
    }


    private void deleteCollection() {
        // 在后台线程上进行网络请求
        OKHttpTool.doNetRequest("prod-api/api/takeout/collect/" + seekUserBean.getId(),
                OKHttpTool.DELETE,
                SeekUserBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        SeekUserBean seekUserBean = (SeekUserBean) obj;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (seekUserBean.getCode() == 200) {
                                    Glide.with(StoreDetailActivity.this).load(R.drawable.shoucang).into(collect);
                                    Toast.makeText(StoreDetailActivity.this, seekUserBean.getMsg(), Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {
                        // 处理失败情况
                    }
                });
    }

    private void setCollection() {
        // 在后台线程上进行网络请求
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("sellerId", recomId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OKHttpTool.doNetRequest("prod-api/api/takeout/collect",
                OKHttpTool.POST,
                SeekUserBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        SeekUserBean seekUserBean = (SeekUserBean) obj;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (seekUserBean.getCode() == 200) {
                                    Glide.with(StoreDetailActivity.this).load(R.drawable.huangixing).into(collect);
                                    Toast.makeText(StoreDetailActivity.this, seekUserBean.getMsg(), Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {
                        // 处理失败情况
                    }
                }, jsonObject.toString());
    }

    ;
}